package test.com.geeksaga.servlet;

import java.io.IOException;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@SuppressWarnings("serial")
public class AnnotationConfigDispatcherServlet extends DispatcherServlet {

    private Class<?>[] classes;

    public AnnotationConfigDispatcherServlet(Class<?>... classes) {
        super();
        this.classes = classes;
    }

    protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
        AbstractRefreshableWebApplicationContext wac = new AbstractRefreshableWebApplicationContext() {
            protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException,
                    IOException {

                AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(beanFactory);
                reader.register(classes);
            }
        };

        wac.setServletContext(getServletContext());
        wac.setServletConfig(getServletConfig());
        wac.refresh();
        return wac;
    }
}